package com.hw.one.collect.spadata.job;

import com.hw.one.collect.spadata.po.MissData;
import com.hw.one.collect.spadata.po.SpaPo;
import com.hw.one.collect.util.SerializeUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/8/22.
 */
@Component
public class SpaRealTimeDataJob extends SpaDataJob {

    private static Logger log = Logger.getLogger(SpaRealTimeDataJob.class);


    public void start() {

        try {

            // 确定一个时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
            String searchTime = sdf.format(new Date());
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("beginTime", searchTime);
            paramMap.put("endTime", searchTime);
            log.info("-----------开始拉取SPA数据【"+searchTime+"】------------------");
            // 执行请求
            List<SpaPo> spaPoList = execute(paramMap);

            // 处理数据
            if (null == spaPoList || spaPoList.size() < 1) {
                log.info("-----------------拉取SPA数据失败【"+searchTime+"】");
                // 未查询到数据，保存到异常数据
                MissData missData = new MissData();
                missData.setMONITORTIME(searchTime);
                missData.setCount(0);
                saveMissData(missData);
            }else if (spaPoList.size() == 1) {
                log.info("-----------------拉取SPA数据成功【"+searchTime+"】");
                // 刚好是一条
                SpaPo spaPo = spaPoList.get(0);
                Serializable serializable = getLastData();
                Object obj = SerializeUtil.unSerialize((byte[]) serializable);
                if (obj instanceof SpaPo) {
                    // 如果是这个类型，开始比较数据
                    SpaPo lastSpa = (SpaPo) obj;
                    if (!lastSpa.getMONITORTIME().equals(spaPo.getMONITORTIME())) {
                        log.info("---------------拉取到的SPA数据跟上次数据不一样，插入-----------");
                        // 监测时间跟上次的数据不一样，插入
                        saveSpaData(spaPo);
                        saveLastData(spaPo);
                    }
                }else {
                    log.info("---------------拉取到的SPA数据，未查询到上次的缓存数据,插入-----------");
                    // 上次的数据有问题，插入此次数据
                    saveSpaData(spaPo);
                    saveLastData(spaPo);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("拉取SPA数据异常----------------", e);
        }
    }


}
